<template>
  <div class="custom-field">
    <el-card style="margin-bottom: 20px;border: none;" shadow="never">
      <div class="custom-field__header">
        <el-form inline>
          <el-form-item label="字段来源表：">
            <el-select
              v-model="selectedOptions.currentTable"
              placeholder="请选择"
              @change="handleSelectChange"
            >
              <el-option
                v-for="item in selectedOptions.list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card style="border: none;" shadow="never">
      <div class="custom-field__header-operation">
        <el-button type="primary" @click="handleOpenDrawer('create')">新建自定义字段</el-button>
      </div>
      <div class="custom-field__body">
        <el-table
          ref="elTableRef"
          v-loading="loading"
          :data="list"
          border
          :header-cell-style="{ background: '#f5f7fa' }"
          height="600"
        >
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="field" label="字段名" align="center" />
          <el-table-column prop="name" label="字段含义" align="center" />
          <el-table-column prop="type" label="字段类型" align="center">
            <template v-slot="{ row }">
              {{ convertFieldsTypeToText(row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="required" label="是否必填" align="center">
            <template v-slot="{ row }">
              <i v-if="row.required" class="el-icon-check icon" />
            </template>
          </el-table-column>
          <el-table-column prop="search" label="是否可搜索" align="center">
            <template v-slot="{ row }">
              <i v-if="row.search" class="el-icon-check icon" />
            </template>
          </el-table-column>
          <el-table-column prop="show" label="是否可展示" align="center">
            <template v-slot="{ row }">
              <i v-if="row.show" class="el-icon-check icon" />
            </template>
          </el-table-column>
          <el-table-column prop="visible" label="是否对员工展示" align="center">
            <template v-slot="{ row }">
              <i v-if="row.visible" class="el-icon-check icon" />
            </template>
          </el-table-column>

          <el-table-column prop="is_interviews" label="是否在面试中收集" align="center">
            <template v-slot="{ row }">
              <i v-if="row.is_interviews" class="el-icon-check icon" />
            </template>
          </el-table-column>

          <el-table-column prop="is_entry" label="是否在入职中收集" align="center">
            <template v-slot="{ row }">
              <i v-if="row.is_entry" class="el-icon-check icon" />
            </template>
          </el-table-column>

          <el-table-column prop="delete" label="是否启用" align="center">
            <template v-slot="{ row }">
              <el-switch
                v-if="row.class !== 1"
                v-model="row.delete"
                :inactive-value="1"
                :active-value="0"
                @change="handleSwitchChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template v-slot="{ row }">
              <el-button
                type="text"
                @click="handleOpenDrawer('edit', row)"
              >编辑</el-button>
              <el-button
                v-if="row.class !== 1"
                type="text"
                style="color: #f56c6c;"
                @click="handleDeleteFields(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-drawer
      :visible.sync="drawerOptions.show"
      size="750px"
      class="custom-field__drawer"
    >
      <template #title>
        <span class="custom-field__drawer--title">{{ drawerOptions.title }}</span>
      </template>
      <div class="custom-field__drawer--form">
        <el-form
          ref="elFormRef"
          :model="formParams"
          label-width="auto"
          :rules="rules"
          :disabled="formParams.class === 1"
        >
          <el-form-item label="字段名(英文)：" prop="field">
            <el-input v-model="formParams.field" placeholder="请输入字段名称" />
          </el-form-item>

          <el-form-item label="字段含义：" prop="name">
            <el-input v-model="formParams.name" placeholder="请输入字段含义" />
          </el-form-item>

          <el-form-item label="字段类型：" prop="type">
            <el-select
              v-model="formParams.type"
              placeholder="请选择"
            >
              <el-option
                v-for="item in fieldsType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="是否可搜索：" prop="search">
            <el-radio-group v-model="formParams.search">
              <el-radio :label="1">可搜索</el-radio>
              <el-radio :label="0">不可搜索</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否展示：" prop="show">
            <el-switch
              v-model="formParams.show"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <el-form-item label="是否必填：" prop="required">
            <el-radio-group v-model="formParams.required">
              <el-radio :label="1">必填</el-radio>
              <el-radio :label="0">选填</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否对员工可见：" prop="visible">
            <el-switch
              v-model="formParams.visible"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <el-form-item label="是否在面试中收集：" prop="is_interviews">
            <el-switch
              v-model="formParams.is_interviews"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <el-form-item label="是否在入职中收集：" prop="is_entry">
            <el-switch
              v-model="formParams.is_entry"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

        </el-form>
      </div>
      <div class="custom-field__drawer-footer">
        <el-button @click="drawerOptions.show = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  editField,
  deleteCustomField,
  enableAndDisableCustomFields,
  addNewCustomFields,
  getFieldsList
} from '@/api/customFields'
export default {
  name: 'CustomFields',
  data() {
    return {
      list: [],
      loading: false,
      selectedOptions: {
        currentTable: 'user_details',
        list: [
          { value: 'user_details', label: '人事档案信息' },
          { value: 'user_companys', label: '企业档案信息' },
          { value: 'interviews', label: '面试信息' },
          { value: 'entry', label: '入职信息' }
        ]
      },
      fieldsType: [
        { value: 'string', label: '文本' },
        // { value: 'number', label: '数值' },
        { value: 'date', label: '时间' },
        // { value: 'img', label: '图片' },
        // { value: 'pdf', label: 'PDF附件' },
        // { value: 'json', label: 'JSON文本' },
        { value: 'file', label: '附件' }
      ],
      drawerOptions: {
        show: false,
        title: '新建自定义字段'
      },
      formParams: {
        table: '',
        field: '',
        type: '',
        name: '',
        search: 1,
        show: 1,
        required: 1,
        visible: 1,
        is_interviews: 0,
        is_entry: 0
      },
      rules: {
        field: [{ required: true, message: '请填写字段名', trigger: ['change', 'blur'] }],
        type: [{ required: true, message: '请选择字段类型', trigger: ['change', 'blur'] }],
        name: [{ required: true, message: '请填写字段含义', trigger: ['change', 'blur'] }],
        search: [{ required: true, message: '请设置是否可搜索', trigger: ['change', 'blur'] }],
        show: [{ required: true, message: '请设置是否可见', trigger: ['change', 'blur'] }],
        visible: [{ required: true, message: '请设置是否对员工可见', trigger: ['change', 'blur'] }],
        required: [{ required: true, message: '请设置是否必填', trigger: ['change', 'blur'] }]
      }
    }
  },
  computed: {
    convertFieldsTypeToText() {
      return (field) => {
        return this.fieldsType.filter(item => item.value === field)[0]?.label
      }
    }
  },
  created() {
    this.init()
  },
  mounted() {
    this.tableReRender()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.elTableRef.doLayout()
    })

    this.tableReRender()
  },
  methods: {
    tableReRender() {
      window.addEventListener('resize', () => {
        this.$nextTick(() => {
          this.$refs.elTableRef.doLayout()
        })
      })
    },
    init() {
      this.getFieldList(this.selectedOptions.currentTable)
    },

    async getFieldList(table) {
      this.loading = true
      const params = { table: JSON.stringify([table]) }
      try {
        const res = await getFieldsList(params)
        this.list = res.data
        this.tableReRender()
      } catch (error) {
        this.$message.error('获取字段列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSelectChange(e) {
      this.getFieldList(e)
    },

    handleOpenDrawer(type, row) {
      this.reset()
      if (type === 'create') {
        this.drawerOptions.title = '新建自定义字段'
      } else {
        this.drawerOptions.title = '编辑自定义字段'
        this.formatterEditData(row)
      }
      this.drawerOptions.show = true
      this.$nextTick(() => {
        this.$refs.elFormRef.clearValidate()
      })
    },

    async handleSubmit() {
      if (this.formParams.class === 1) {
        this.drawerOptions.show = false
        return this.$message.error('系统字段不可编辑')
      }
      try {
        await this.$refs.elFormRef.validate()
        if (!this.formParams.id) {
          await this.addNewFieldsApi({
            ...this.formParams,
            table: this.selectedOptions.currentTable
          })
        } else {
          await this.editFieldApi(this.formParams)
        }
      } catch (error) {
        this.$message.error('请填写完整信息')
      }
    },

    formatterEditData(data) {
      console.log('data --------->', data)
      Object.keys(this.formParams).forEach(item => {
        this.formParams[item] = data[item]
      })
      this.formParams.class = data.class
      this.formParams.id = data.id
    },

    async addNewFieldsApi(data) {
      try {
        const res = await addNewCustomFields(data)
        if (res.code === 200) {
          this.$message.success('添加成功')
          this.refresh()
        }
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '创建自定义字段失败')
      }
    },

    async editFieldApi(data) {
      try {
        const res = await editField(data)
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.refresh()
        }
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改自定义字段失败')
      }
    },

    handleDeleteFields(row) {
      const ids = JSON.stringify([row.id])
      this.$confirm(
        '是否删除该字段',
        {
          type: 'warning',
          cancelButtonText: '取消',
          confirmButtonText: '确定'
        }
      ).then(() => {
        this.deleteFieldsApi(ids)
      })
    },

    async deleteFieldsApi(ids) {
      try {
        const res = await deleteCustomField({ id: ids })
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.refresh()
        }
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '删除失败')
      }
    },

    async handleSwitchChange(row) {
      try {
        const res = await enableAndDisableCustomFields({ id: row.id })
        if (res.code === 200) {
          this.$message.success('切换成功')
        }
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '切换失败')
      }
    },

    reset() {
      this.formParams = this.$options.data().formParams
    },

    refresh() {
      this.drawerOptions.show = false
      this.getFieldList(this.selectedOptions.currentTable)
    },

    handleChangeIsInterview(row) {
      console.log('row handleChangeIsInterview--------->', row)
      const params = {
        is_interviews: row.is_interviews === 0 ? 1 : 0
      }
      this.editFieldApi(params)
    },

    handleChangeIsEntry(row) {
      console.log('row handleChangeIsEntry--------->', row)
    }

  }
}
</script>
<style lang="scss" scoped>
.custom-field {
  padding: 20px;

  &__header {
    ::v-deep(.el-form-item) {
      margin-bottom: 0;
    }
  }

  .icon {
    font-size: 18px;
  }
  &__header-operation {
    margin-bottom: 20px;
  }
  &__drawer {
    &--title {
      font-weight: bold;
      font-size: 20px;
      color: #333;
    }

    &--form {
      width: 70%;
      .el-select {
        width: 100%;
      }
    }

    &-footer {
      display: flex;
      justify-content: center;
      align-items: center;
      border-top: 1px solid #ececec;
      padding: 30px 0;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
    }

  }
}
:deep(.el-drawer__body) {
  position: relative;
  padding: 20px 20px 0 50px;
}
</style>
